from Oa_system.models import classification_cement, notification, news_management, Staffing
from administrative.models import Company, Topicsattachments, Topics
from announcements.models import Notice, AuditRecord, NoticePeople
from ios_api.models import ScanCode
from logistics.MessagePushOperationRecords import RecordAndPush
from django.shortcuts import render, HttpResponse, redirect
from personal_center.creat_excel import create_table
from django.utils.encoding import escape_uri_path
from administrative.public_file import ParseWord
from django.http import StreamingHttpResponse
from administrative.utils import send_mssage
from personal_center.process_check import *
from personal_center.models import User
from personal_center.sql_file import *
from announcements import public_file
from back_management.models import *
from correspondence.models import *
from django.db import connection
from PyPDF2 import PdfFileMerger
from operator import itemgetter
from django.db.models import Q
from django.views import View
from datetime import datetime
import uuid, xlrd, shutil



# 文件下载
class file_download(View):
    def get(self, request):
        file_name = request.GET.get("file_path", None)
        # file_path = os.path.join(os.getcwd().replace("\\", "/"), file_name)
        file_path = os.getcwd().replace("\\", "/") + file_name.replace(os.getcwd(), "")
        print(file_path)
        def file_iterator(file_path, chunk_size=512):
            with open(file_path, mode='rb') as f:
                while True:
                    c = f.read(chunk_size)
                    if c:
                        yield c
                    else:
                        break

        response = StreamingHttpResponse(file_iterator(file_path))
        # 以流的形式下载文件,这样可以实现任意格式的文件下载
        response['Content-Type'] = 'application/octet-stream'
        # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
        print(file_name.split("/")[-1])
        response["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(escape_uri_path(file_name.split("/")[-1]))
        return response


class Announcements(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, 'announcements/announcements.html',{'realname': real_name, 'position': position, 'department': department})


# 通知首页
class home(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, 'announcements/index.html',{'realname': real_name, 'position': position, 'department': department})


# 公告管理
class administration(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'announcements/administration.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        if user.username != 'admin':
            objs = user.noticepeople_set.filter(notice_id__state='end').order_by('-create_time')
            # accept_n = [i.notice_id for i in user.noticepeople_set.all() if i.notice_id.state == 'audit']
            data_list = [
                {'id': obj.notice_id.id, 'is_open': f"<strong>{obj.notice_id.is_open}</strong>" if obj.state == 'accept' else obj.notice_id.is_open,
                 'department': f"<strong>{obj.notice_id.create_people.department}</strong>" if obj.state == 'accept' else obj.notice_id.create_people.department,
                 # 'status': temp.state,
                 'create_user': f"<strong>{obj.notice_id.create_people.real_name}</strong>" if obj.state == 'accept' else obj.notice_id.create_people.real_name,
                 'create_time': f"<strong>{obj.notice_id.update_time.strftime('%Y-%m-%d %H:%M')}</strong>" if obj.state == 'accept' else obj.notice_id.update_time.strftime("%Y-%m-%d %H:%M"),
                 'titile': f"<strong>{obj.notice_id.name}</strong>" if obj.state == 'accept' else obj.notice_id.name} for
                obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        else:
            objs = Notice.objects.filter(state='audit').order_by('-create_time')
            print("===============================")
            data_list = [{'id': temp.id, 'is_open': temp.is_open,
                          'department': temp.create_people.department,
                          # 'status': temp.state,
                          'create_user': temp.create_people.real_name,
                          'create_time': temp.update_time.strftime("%Y-%m-%d %H:%M"), 'titile': temp.name} for
                         temp in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 新增公告
class newly_increased(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
            leaders = [request.user.company.leaders_id]
            if request.user.company.id in (3, 80):
                com_objs = Company.objects.filter(id__in=[3, 80])
                leaders = [record.leaders_id for record in com_objs]
        except:
            return redirect("/")
        return render(request, 'announcements/newly_increased.html',
                      {'realname': real_name, 'position': position, 'department': department, 'leaders': leaders, "uuid": uuid.uuid4()})

    def post(self, request):
        returnDict, option_list, returnList = {}, [], []
        cement_name = request.POST.get("cement_name", None)         # 公告名称
        genre = request.POST.get("genre", None)             # 所属类型
        notice_date = request.POST.get("notice_date", None)         # 公告日期
        switchs = request.POST.get("switchs", None)             # 是否公开
        recipient = request.POST.get("recipient", None)         # 接收人
        editor_html = request.POST.get("editor_html", None)         # 公告正文
        file_list = request.POST.get('file_list', None)  # 附件

        if cement_name:
            editor_html = base64.b64encode(editor_html.encode("utf-8")).decode()
            notification.objects.create(name=cement_name, category=genre, open=switchs, accept_people=recipient,
                                        content=editor_html, announcement_time=notice_date.replace("T", ' '),
                                        adjunct=json.dumps(file_list), create_people=request.user.real_name)


        option_data = classification_cement.objects.all()
        for option in option_data:
            option_list.append(option.name)

        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["option_list"] = option_list
        returnDict["data"] = returnList
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NoticeIndex(View):
    def post(self, request):
        name = request.POST.get("name", None)
        is_open = request.POST.get("switchs", None)
        accept_people = request.POST.get("recipient", None)
        content = request.POST.get("content", None)
        fg_people = request.POST.get("fg_people", None)
        uuid_str = request.POST.get("uuid", None)
        user = request.user
        if not fg_people:
            returnDict = {'code': 500, 'message': '该员工所属部门未挂分管领导'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if name and content:
            content = base64.b64encode(content.encode("utf-8")).decode()
            audit_people_obj = User.objects.get(id=int(fg_people))
            if audit_people_obj:
                notice_obj = Notice.objects.create(name=name, is_open=is_open, content=content, create_people=user, audit_people=audit_people_obj, uuid=uuid_str)
            else:
                returnDict = {'code': 500, 'message': '未找到分管领导，请联系管理员检查'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'code': 500, 'message': '请填写公告名称和内容'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if notice_obj:
            NoticePeople_list = []
            if accept_people:
                accept_people = re.findall('\((.*?)\)', accept_people)
                accept_people_objs = User.objects.filter(job_number__in=accept_people)
            else:
                accept_people_objs = User.objects.all()

            for accept_people_obj in accept_people_objs:
                NoticePeople_obj = NoticePeople(notice_id=notice_obj, audit_people=accept_people_obj)
                NoticePeople_list.append(NoticePeople_obj)

            NoticePeople.objects.bulk_create(NoticePeople_list)
            achments_objs = Topicsattachments.objects.filter(topics_number=notice_obj.uuid)
            for achments_obj in achments_objs:
                achments_obj.watch_users.add(audit_people_obj)
                for r in notice_obj.noticepeople_set.all():
                    if r.audit_people not in achments_obj.watch_users.all():
                        achments_obj.watch_users.add(r.audit_people)
                    # notice_obj.accept_people.add(accept_people_obj)
                    # NoticePeople.objects.create(notice_id=notice_obj, audit_people=accept_people_obj)
            AuditRecord.objects.create(notice_id=notice_obj, audit_people=audit_people_obj, audit_note='', state='unaudit', node="one")
            AuditRecord.objects.create(notice_id=notice_obj, audit_people=Company.objects.get(id=80).head_people, audit_note='', state='unaudit', node="two")
            notice_obj.current_audit_users.add(audit_people_obj)
            notice_obj.state = "one"
            notice_obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "通知公告"
            applicant = notice_obj.create_people.real_name
            ApplicationTime = notice_obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = notice_obj.name[:15] + "……" if len(notice_obj.name) > 15 else notice_obj.name
            try:
                RecordAndPush().MessagePush(notice_obj.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        else:
            returnDict = {'code': 500, 'message': '创建失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NoticeList(View):
    def get(self, request):
        user = request.user
        real_name = user.real_name
        position = user.position
        department = user.department
        # 改为我的申请列表

        return render(request, 'announcements/newly_increased_apply_list.html',
                      {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.Notice_create_people.all().order_by("-id")
        data_list = [{'id': notice_obj.id, 'name': notice_obj.name, 'create_people': user.real_name,
                      'company': user.company.name, 'state': notice_obj.get_state_display(),
                      'current_people': notice_obj.audit_people.real_name if notice_obj.audit_people else ''
                      } for notice_obj in
                     objs[(int(page) - 1) * 20:int(page) * 20]]

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NoticeAuditList(View):
    def get(self, request):
        user = request.user
        real_name = user.real_name
        position = user.position
        department = user.department
        # 改为我的待办我的已办列表
        return render(request, 'announcements/Notice_Managerment.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'audit')  # audit 我的待办 already 我的已办
        if tab == 'audit':
            objs = user.Notice_audit_people.all().order_by("-id")
        else:
            objs = user.notice_already_users.all().order_by("-id")

        data_list = [
            {'id': notice_obj.id, 'name': notice_obj.name, 'create_people': notice_obj.create_people.real_name,
             'company': user.company.name, 'state': notice_obj.get_state_display(),
             'current_people': notice_obj.audit_people.real_name if notice_obj.audit_people else '',
             'announcement_time': notice_obj.create_time.strftime('%Y-%m-%d %H:%M')} for notice_obj in
            objs]

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NoticeDetail(View):
    def post(self, request):
        id = request.POST.get("id", None)
        user = request.user

        notice_obj = Notice.objects.get(id=int(id))

        if notice_obj.state == 'end':
            notice_people_obj = notice_obj.noticepeople_set.filter(audit_people=user, state='accept').first()
            if notice_people_obj:
                notice_people_obj.state = 'accepted'
                notice_people_obj.accepted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                notice_people_obj.save()

        notice_people_list = []
        sql = "SELECT B.real_name, B.signature_picture, A.accepted_time, A.state FROM announcements_noticepeople A LEFT JOIN tb_users_message B ON A.audit_people_id=B.id WHERE A.notice_id_id=%(notice_id)s"
        with connection.cursor() as cursor:
            cursor.execute(sql, {'notice_id': id})
            noticepeople_all = cursor.fetchall()
        for notice_people in noticepeople_all:
            one_dict = {'name': notice_people[0], 'state': '未读' if notice_people[3] == 'accept' else '已读', 'accepted_time': notice_people[2] if notice_people[3] == 'accepted' else '', 'signature_picture': '/media/' + notice_people[1] if notice_people[3]=='accepted' and notice_people[1] else ''}
            notice_people_list.append(one_dict)

        returnData = {'code': 200, 'message': 'success',
                      'return_dic': {'create_people': notice_obj.create_people.real_name,
                                     'create_people_company': notice_obj.create_people.company.name,
                                     'title': notice_obj.name,
                                     'state': notice_obj.get_state_display(),
                                     'creat_time': str(notice_obj.create_time).split(".")[0][:-3],
                                     'is_open': notice_obj.is_open,
                                     'type': notice_obj.type,
                                     "uuid_str": notice_obj.uuid,
                                     'content': base64.b64decode(notice_obj.content).decode(),
                                     'adjunct': [{"file_name": i.file_name, "file_path": str(i.pdf_path), "file_size": i.file_size, "upload_time": i.create_time.strftime("%Y-%m-%d %H:%M"),
                                                  "upload_people": i.uploader_user.real_name, 'id': i.id, 'download_path': f'/media/{str(i.file_path)}'} for i in Topicsattachments.objects.filter(topics_number=notice_obj.uuid)]},
                      'notice_people_list': notice_people_list,
                      'audit_people_list': [{"name": i.audit_people.real_name, "state": i.get_state_str(), "accepted_time": i.create_time.strftime("%Y-%m-%d %H:%M"), "audit_note": i.audit_note,
                                             "signature_picture": "" if i.get_state_str() == '待审核' else str(i.audit_people.signature_picture)} for i in notice_obj.auditrecord_set.all()],
                      }

        print(returnData['audit_people_list'])
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class AuditNotice(View):
    def post(self, request):
        id = request.POST.get("id", None)
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        audit_note = request.POST.get("audit_note", "同意")
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            notice_obj = Notice.objects.get(id=int(id))
            notice_obj.audit_users_already.add(request.user)
            if notice_obj.state == 'one':
                notice_obj.current_audit_users.clear()
                audit_record = notice_obj.auditrecord_set.filter(node='one', state='unaudit').first()
                if state == 'audit':
                    next_audit_record = notice_obj.auditrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                    notice_obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'eight'
                    notice_obj.current_audit_users.add(notice_obj.create_people)

            elif notice_obj.state == 'two':
                notice_obj.current_audit_users.clear()
                audit_record = notice_obj.auditrecord_set.filter(node='two', state='unaudit').first()
                if state == 'audit':
                    obj_state = 'end'
                else:
                    obj_state = 'eight'
                    notice_obj.current_audit_users.add(notice_obj.create_people)

            else:
                returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        except Exception as e:
            print(e)
            returnData = {'code': 500, 'message': '审批错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        notice_obj.state = obj_state
        notice_obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        returnData = {'code': 200, 'message': 'success！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class NoticeWriteView(View):
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        is_open = request.POST.get("switchs", None)
        accept_people = request.POST.get("recipient", None)
        content = request.POST.get("content", None)
        file_list = request.POST.get('file_list', None)  # 附件

        obj = Notice.objects.get(id=int(id))
        obj.auditrecord_set.filter(state="unaudit").delete()
        if obj.state != 'eight':
            returnData = {'code': 500, 'message': '修改错误，只有为拒绝状态的公告才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            if is_open:
                obj.is_open = is_open
            NoticePeople_list = []
            if accept_people:
                accept_people = re.findall('\((.*?)\)', accept_people)
                accept_people_objs = User.objects.filter(job_number__in=accept_people)
            else:
                accept_people_objs = User.objects.all()

            for accept_people_obj in accept_people_objs:
                NoticePeople_obj = NoticePeople(notice_id=obj, audit_people=accept_people_obj)
                NoticePeople_list.append(NoticePeople_obj)
            NoticePeople.objects.bulk_create(NoticePeople_list)
            if content:
                obj.content = base64.b64encode(content.encode("utf-8")).decode()
            if file_list:
                obj.file_list = json.dumps(file_list)

            AuditRecord.objects.create(notice_id=obj, audit_people=obj.audit_people, audit_note='', state='unaudit', node="one")
            AuditRecord.objects.create(notice_id=obj, audit_people=Company.objects.get(id=80).head_people, audit_note='', state='unaudit', node="two")
            obj.current_audit_users.add(obj.audit_people)
            obj.state = "one"
            obj.save()
            returnDict = {'code': 200, 'message': '修改成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        except Exception as e:
            print(e)
            obj.state = 'unaudit'
            obj.save()
            returnData = {'code': 500, 'message': '修改错误'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class NoticeBackView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)
        audit_people = request.POST.get('audit_people', None)

        audit_people_list = re.findall('\((.*?)\)', audit_people)
        audit_people_objs = User.objects.filter(job_number__in=audit_people_list).first()

        obj = Notice.objects.get(id=int(id))
        if state == obj.state:
            returnData = {'code': 200, 'message': 'ok！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            if state == 'draft':
                np_objs = obj.noticepeople_set.all()
                for np_obj in np_objs:
                    np_obj.state = 'accept'
                    np_obj.save()
                obj.audit_people = audit_people_objs
                audit_objs = obj.auditrecord_set.all()
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'unaudit':
                obj.audit_people = obj.create_people
                np_objs = obj.noticepeople_set.all()
                for np_obj in np_objs:
                    np_obj.state = 'accept'
                    np_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                returnData = {'code': 500, 'message': '请选择正确的状态！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")


# 查看公告详情
class detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        content_id = request.GET.get("id", None)
        request_type = request.GET.get("type", None)

        if request_type == "xinwen":
            content_data = news_management.objects.get(id=content_id)
            title = content_data.name                   # 公告名称
            announcement_time = content_data.release_time  # 发布时间
            file_list = content_data.adjunct
            nav_one = "新闻管理"
            nav_two = "新闻详情"
            a_href = "news_manage.html"
            navLeft = "news-administration"
            content_data_content = base64.b64decode(content_data.content).decode()
            try:
                content_text = ''
                for i in re.findall("<img(.*?)>", base64.b64decode(content_data_content).decode(), re.S):
                    old_url = re.findall("src=\"(.*?)\"", i)[0]
                    new_url = re.findall("src=\"(.*?)\"", i)[0].replace(" ", "%2B")
                    content_text = content_data_content.replace(old_url, new_url)
            except:
                content_text = content_data_content

        else:
            content_data = notification.objects.get(id=content_id)
            content_data_content = base64.b64decode(content_data.content).decode()
            readId_str = content_data.readId

            if str(request.user.id) not in readId_str.split(","):
                content_data.readId = readId_str+str(request.user.id)+","
                content_data.save()

            title = content_data.name               # 公告名称
            announcement_time = content_data.announcement_time          # 发布时间
            if content_data.adjunct:
                file_list = json.loads(content_data.adjunct)
            else:
                file_list = ""
            nav_one = "通知公告"
            nav_two = "通知详情"
            a_href = "administration.html"
            navLeft = "Announcement-management"
            try:
                old_url = re.findall("src=\"(.*?)\"", re.findall("<img(.*?)>", content_data_content, re.S)[0])[0]
                new_url = re.findall("src=\"(.*?)\"", re.findall("<img(.*?)>", content_data_content, re.S)[0])[0].replace(" ", "%2B")
                content_text = content_data_content.replace(old_url, new_url)
            except:
                content_text = content_data_content


        returnData = {'realname': real_name, 'position': position, 'department': department, "title": title, "announcement_time": announcement_time,
                      "content_text": content_text.replace("%26nbsp;", "&nbsp;").replace("src=\"", "src=\"http://hbjsxrmyy.com"),
                      "file_list": json.loads(file_list) if file_list else [],
                      "nav_one": nav_one, "nav_two": nav_two, "a_href": a_href, "navLeft": navLeft}

        return render(request, 'announcements/detail.html', returnData)


# 图片上传
class upload_img(View):
    def post(self, request):
        returnDict = {}
        file_path = os.path.join(os.getcwd(), 'static/announcements/upload_imgs')
        myFiles = request.FILES.get("file", None)
        if not os.path.exists(file_path):
            os.mkdir(file_path)

        with open(os.path.join(file_path, myFiles.name), "wb") as F:
            for i in myFiles.chunks():
                F.write(i)

        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["data"] = [{"img-url": f"../../static/announcements/upload_imgs/{myFiles.name}"}]
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 上传附件
class upload_accessory(View):
    def post(self, request):
        returnDict = {}
        file_path = os.path.join(os.getcwd(), 'static/announcements/UploadAccessory')
        myFiles = request.FILES.get("file", None)
        if not os.path.exists(file_path):
            os.mkdir(file_path)

        with open(os.path.join(file_path, myFiles.name), "wb") as F:
            for i in myFiles.chunks():
                F.write(i)

        word_path = os.path.join(os.getcwd(), f"static/announcements/UploadAccessory/{myFiles.name}")

        if 'xls' == word_path.split(".")[-1]:
            os.rename(word_path, word_path+"x")
            word_path = word_path+"x"


        if word_path.split('.')[-1] in ['docx', 'doc']:
            pdf_path = ParseWord().word2pdf(word_path)
        elif word_path.split(".")[-1] in ['ppt', 'pptx']:
            pdf_path = ParseWord().ppt2pdf(word_path)
        elif word_path.split(".")[-1] in ['xlsx', 'xls']:
            pdf_path = ParseWord().create_pdf(word_path, myFiles.name)
            aaa_list = []
            for i in pdf_path:
                aaa_list.append(i.replace(os.getcwd(), "").replace("\\", '/'))
            pdf_path = aaa_list
        else:
            pdf_path = word_path.replace(os.getcwd(), "").replace("\\", '/')

        accessory_dict = {}
        accessory_dict["accessory_url"] = f"static/announcements/UploadAccessory/{myFiles.name}"
        accessory_dict["accessory_name"] = myFiles.name
        accessory_dict["upload_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        accessory_dict["file_size"] = public_file.StrOfSize(myFiles.size)
        accessory_dict["pdf_path"] = pdf_path
        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["data"] = [accessory_dict]
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 公告管理：我的申请 我的审批
class Notice_Managerment(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returnData = {'realname': real_name, 'position': position, 'department': department}

        return render(request, 'announcements/Notice_Managerment.html', returnData)


# 公告统计
class proclamation_statistics(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returnData = {'realname': real_name, 'position': position, 'department': department}

        return render(request, 'announcements/proclamation_statistics.html', returnData)


class notice_detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        types = request.GET.get("type", None)
        all_flag = ""
        if types:
            all_flag = True
        returnData = {'realname': real_name, 'position': position, 'department': department, "all_flag": all_flag}

        return render(request, 'announcements/notice_detail.html', returnData)


class notice_approve(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = Notice.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.auditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.auditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime( "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"), "file_size": atta_obj.file_size,
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.uuid)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.create_people == request.user) else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'eight'] and request.user == obj.create_people else 'false',
                   'flow_dict': flow_dict, "countent": urllib.parse.unquote(base64.b64decode(base64.b64decode(obj.content).decode()).decode()),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.uuid) else ""
                   }
        return render(request, 'announcements/notice_approve.html', context)


class list_query(View):
    def post(self, request):
        page = request.POST.get('page', 1)
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20
        id = request.POST.get('search_type', None)
        company_ids = request.POST.get('search_table', None)  # 科室列表id ['3','4','5']
        if company_ids == "车辆申请":
            select_sql = "SELECT * from (SELECT '车辆申请' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'fg' then '审核中' when a.state = 'ybzr' then '审核中' when a.state = 'cgb' then '完结' when a.state = 'done' then '完结'when a.state = 'cancel' then '作废' END as state, au.real_name as audit_user, a.update_time as audit_time, a.`subject` as title from administrative_vehicleapply a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN tb_users_message au on au.id = a.current_audit_user_id LEFT JOIN administrative_vehicleapply_already_users am on am.vehicleapply_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '车辆申请' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'fg' then '审核中' when a.state = 'ybzr' then '审核中' when a.state = 'cgb' then '完结' when a.state = 'done' then '完结'when a.state = 'cancel' then '作废' END as state, au.real_name as audit_user, a.update_time as audit_time, a.`subject` as title from administrative_vehicleapply a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN tb_users_message au on au.id = a.current_audit_user_id LEFT JOIN administrative_vehicleapply_already_users am on am.vehicleapply_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
        elif company_ids == "通知公告":
            select_sql = "SELECT * from (SELECT '通知公告' as classification, u.id as id, u.create_time as create_time, c.real_name as apply_user, c.department as company, case when A.state = 'draft' then '退回' when A.state = 'audit' then '完结' when A.state = 'unaudit' then '审核中' END as state, au.real_name as audit_user, u.update_time as audit_time, u.`name` as title from announcements_auditrecord	A LEFT JOIN announcements_notice u on A.notice_id_id = u.id LEFT JOIN tb_users_message c on u.create_people_id = c.id LEFT JOIN tb_users_message au on au.id = u.audit_people_id where A.audit_people_id = %(already_users)s AND A.state in ('audit', 'draft') GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '通知公告' as classification, u.id as id, u.create_time as create_time, c.real_name as apply_user, c.department as company, case when A.state = 'draft' then '退回' when A.state = 'audit' then '完结' when A.state = 'unaudit' then '审核中' END as state, au.real_name as audit_user, u.update_time as audit_time, u.`name` as title from announcements_auditrecord	A LEFT JOIN announcements_notice u on A.notice_id_id = u.id LEFT JOIN tb_users_message c on u.create_people_id = c.id LEFT JOIN tb_users_message au on au.id = u.audit_people_id where A.audit_people_id = %(already_users)s AND A.state in ('audit', 'draft') GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
        elif company_ids == "党委会议题":
            select_sql = "SELECT * from (SELECT '党委会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN administrative_topics_already_users am on am.topics_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s and a.type = 'db' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '党委会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN administrative_topics_already_users am on am.topics_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s and a.type = 'db' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
        elif company_ids == "院长办公会议题":
            select_sql = "SELECT * from (SELECT '院长办公会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN administrative_topics_already_users am on am.topics_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s and a.type = 'yb' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '院长办公会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN administrative_topics_already_users am on am.topics_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s and a.type = 'yb' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
        elif company_ids == "行政例会议题":
            select_sql = "SELECT * from (SELECT '行政例会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN administrative_topics_already_users am on am.topics_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s and a.type = 'xz' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '行政例会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN administrative_topics_already_users am on am.topics_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s and a.type = 'xz' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
        elif company_ids == "党委会议纪要":
            select_sql = "SELECT * from (SELECT '党委会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'a' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '党委会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'a' GROUP BY classification, id, create_time, apply_user, company, state) base "
        elif company_ids == "院长办公会会议纪要":
            select_sql = "SELECT * from (SELECT '院长办公会会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'b' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '院长办公会会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'b' GROUP BY classification, id, create_time, apply_user, company, state) base "
        elif company_ids == "党委专题会议纪要":
            select_sql = "SELECT * from (SELECT '党委专题会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'c' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '党委专题会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'c' GROUP BY classification, id, create_time, apply_user, company, state) base "
        elif company_ids == "院长办公会专题会议纪要":
            select_sql = "SELECT * from (SELECT '院长办公会专题会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'd' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '院长办公会专题会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'd' GROUP BY classification, id, create_time, apply_user, company, state) base"
        elif company_ids == "行政例会简报":
            select_sql = "SELECT * from (SELECT '行政例会简报' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'e' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '行政例会简报' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'e' GROUP BY classification, id, create_time, apply_user, company, state) base"
        elif company_ids == "行政公文(京医文)":
            select_sql = "SELECT * from (SELECT '行政公文(京医文)' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'h' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '行政公文(京医文)' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'h' GROUP BY classification, id, create_time, apply_user, company, state) base"
        elif company_ids == "党委公文":
            select_sql = "SELECT * from (SELECT '党委公文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'g' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '党委公文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'g' GROUP BY classification, id, create_time, apply_user, company, state) base"
        elif company_ids == "行政公文(京医发)":
            select_sql = "SELECT * from (SELECT '行政公文(京医发)' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'f' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '行政公文(京医发)' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s AND a.type = 'f' GROUP BY classification, id, create_time, apply_user, company, state) base"
        else:
            select_sql = "SELECT * from (SELECT '上级来文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.type = 'a' then '审核中' when a.type = 'b' then '审核中' when a.type = 'c' then '审核中' when a.type = 'h' then '审核中' when a.type = 'd' then '传阅中' when a.type = 'e' then '完结' when a.type = 'f' then '退回' when a.type = 'g' then '待分发' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.title as title FROM administrative_officialdocuments a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_officialdocuments_current_audit_users m on m.officialdocuments_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_officialdocuments_audit_users_already am on am.officialdocuments_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '上级来文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.type = 'a' then '审核中' when a.type = 'b' then '审核中' when a.type = 'h' then '审核中' when a.type = 'c' then '审核中' when a.type = 'd' then '传阅中' when a.type = 'e' then '完结' when a.type = 'f' then '退回' when a.type = 'g' then '待分发' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.title as title FROM administrative_officialdocuments a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_officialdocuments_current_audit_users m on m.officialdocuments_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id LEFT JOIN administrative_officialdocuments_audit_users_already am on am.officialdocuments_id = a.id left join tb_users_message already_user on already_user.id = am.user_id where already_user.id = %(already_users)s GROUP BY classification, id, create_time, apply_user, company, state) base "

        with connection.cursor() as cursor:
            cursor.execute(select_sql,
                           {'already_users': request.user.id})
            rows1 = cursor.fetchall()
            cursor.execute(select_count_sql, {'already_users': request.user.id})
            rows1_num = cursor.fetchone()

        data1 = []
        a2, b2, c2, d2, e2, f2 = [], [], [], [], [], []
        for row in rows1:
            row_dict = {
                'classification': row[0],
                'id': row[1],
                'create_time': row[2].strftime("%Y-%m-%d %H:%M"),
                'apply_user': row[3],
                'company': row[4],
                'state': row[5],
                'audit_user': row[6],
                'title': row[8],
                'audit_time': row[7].strftime("%Y-%m-%d %H:%M")
            }
            if row[5] == "审核中":
                a2.append(row_dict)
            elif row[5] == "待分发":
                b2.append(row_dict)
            elif row[5] == "传阅中":
                c2.append(row_dict)
            elif row[5] == "退回":
                e2.append(row_dict)
            elif row[5] == "作废":
                f2.append(row_dict)
            else:
                d2.append(row_dict)
            data1 = a2 + b2 + c2 + e2 + f2 + d2
        print('>>>>>>>', rows1_num[0])
        returnDict = {'code': 200, 'message': '操作成功', "data": data1[num1:num2], "num": rows1_num[0]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class sq_list_query(View):
    def post(self, request):
        page = request.POST.get('page', 1)
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20
        id = request.POST.get('search_type', None)
        company_ids = request.POST.get('search_table', None)  # 科室列表id ['3','4','5']
        if company_ids == "车辆申请":
            select_sql = "SELECT * from (SELECT '车辆申请' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'fg' then '审核中' when a.state = 'ybzr' then '审核中' when a.state = 'cgb' then '完结' when a.state = 'done' then '完结'when a.state = 'cancel' then '作废' END as state, au.real_name as audit_user, a.update_time as audit_time, a.`subject` as title from administrative_vehicleapply a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN tb_users_message au on au.id = a.current_audit_user_id where a.apply_user_id = %(apply_user)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '车辆申请' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'fg' then '审核中' when a.state = 'ybzr' then '审核中' when a.state = 'cgb' then '完结' when a.state = 'done' then '完结'when a.state = 'cancel' then '作废' END as state, au.real_name as audit_user, a.update_time as audit_time, a.`subject` as title from administrative_vehicleapply a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN tb_users_message au on au.id = a.current_audit_user_id where a.apply_user_id = %(apply_user)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
        elif company_ids == "通知公告":
            select_sql = "SELECT * from (SELECT '通知公告' as classification, u.id as id, u.create_time as create_time, c.real_name as apply_user, c.department as company, case when A.state = 'draft' then '退回' when A.state = 'audit' then '完结' when A.state = 'unaudit' then '审核中' END as state, au.real_name as audit_user, u.update_time as audit_time, u.`name` as title from announcements_auditrecord	A LEFT JOIN announcements_notice u on A.notice_id_id = u.id LEFT JOIN tb_users_message c on u.create_people_id = c.id LEFT JOIN tb_users_message au on au.id = u.audit_people_id where A.create_people_id = %(apply_user)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '通知公告' as classification, u.id as id, u.create_time as create_time, c.real_name as apply_user, c.department as company, case when A.state = 'draft' then '退回' when A.state = 'audit' then '完结' when A.state = 'unaudit' then '审核中' END as state, au.real_name as audit_user, u.update_time as audit_time, u.`name` as title from announcements_auditrecord	A LEFT JOIN announcements_notice u on A.notice_id_id = u.id LEFT JOIN tb_users_message c on u.create_people_id = c.id LEFT JOIN tb_users_message au on au.id = u.audit_people_id where A.create_people_id = %(apply_user)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
        elif company_ids == "党委会议题":
            select_sql = "SELECT * from (SELECT '党委会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id where a.employee_id = %(apply_user)s AND a.type = 'db' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '党委会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id where a.employee_id = %(apply_user)s AND a.type = 'db' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "院长办公会议题":
            select_sql = "SELECT * from (SELECT '院长办公会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id where a.employee_id = %(apply_user)s AND a.type = 'yb' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '院长办公会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id where a.employee_id = %(apply_user)s AND a.type = 'yb' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "行政例会议题":
            select_sql = "SELECT * from (SELECT '行政例会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id where a.employee_id = %(apply_user)s AND a.type = 'xz' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '行政例会议题' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id where a.employee_id = %(apply_user)s AND a.type = 'xz' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "党委会议纪要":
            select_sql = "SELECT * from (SELECT '党委会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'a' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '党委会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'a' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time descs"

        elif company_ids == "院长办公会会议纪要":
            select_sql = "SELECT * from (SELECT '院长办公会会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'b' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '院长办公会会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'b' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "党委专题会议纪要":
            select_sql = "SELECT * from (SELECT '党委专题会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'c' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '党委专题会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'c' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "院长办公会专题会议纪要":
            select_sql = "SELECT * from (SELECT '院长办公会专题会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'd' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '院长办公会专题会议纪要' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'd' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "行政例会简报":
            select_sql = "SELECT * from (SELECT '行政例会简报' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'e' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '行政例会简报' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'e' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "行政公文(京医文)":
            select_sql = "SELECT * from (SELECT '行政公文(京医文)' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'h' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '行政公文(京医文)' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'h' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "党委公文":
            select_sql = "SELECT * from (SELECT '党委公文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'g' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '党委公文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'g' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        elif company_ids == "行政公文(京医发)":
            select_sql = "SELECT * from (SELECT '行政公文(京医发)' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'f' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '行政公文(京医发)' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s AND a.type = 'f' GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"

        else:
            select_sql = "SELECT * from (SELECT '上级来文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.type = 'a' then '审核中' when a.type = 'b' then '审核中' when a.type = 'h' then '审核中' when a.type = 'c' then '审核中' when a.type = 'd' then '传阅中' when a.type = 'e' then '完结' when a.type = 'f' then '退回' when a.type = 'g' then '待分发' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.title as title FROM administrative_officialdocuments a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_officialdocuments_current_audit_users m on m.officialdocuments_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"
            select_count_sql = "SELECT count(*) as num from (SELECT '上级来文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.type = 'a' then '审核中' when a.type = 'b' then '审核中' when a.type = 'h' then '审核中' when a.type = 'c' then '审核中' when a.type = 'd' then '传阅中' when a.type = 'e' then '完结' when a.type = 'f' then '退回' when a.type = 'g' then '待分发' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.title as title FROM administrative_officialdocuments a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_officialdocuments_current_audit_users m on m.officialdocuments_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where a.apply_user_id = %(apply_user)s GROUP BY classification, id, create_time, apply_user, company, state) base ORDER BY create_time desc"


        with connection.cursor() as cursor:
            cursor.execute(select_sql, {'apply_user': request.user.id})
            rows1 = cursor.fetchall()
            cursor.execute(select_count_sql, {'apply_user': request.user.id})
            rows1_num = cursor.fetchone()

        data1 = []
        a2, b2, c2, d2, e2, f2 = [], [], [], [], [], []
        for row in rows1:
            row_dict = {
                'classification': row[0],
                'id': row[1],
                'create_time': row[2].strftime("%Y-%m-%d %H:%M"),
                'apply_user': row[3],
                'company': row[4],
                'state': row[5],
                'audit_user': row[6],
                'title': row[8],
                'audit_time': row[7].strftime("%Y-%m-%d %H:%M")
            }
            if row[5] == "审核中":
                a2.append(row_dict)
            elif row[5] == "待分发":
                b2.append(row_dict)
            elif row[5] == "传阅中":
                c2.append(row_dict)
            elif row[5] == "退回":
                e2.append(row_dict)
            elif row[5] == "作废":
                f2.append(row_dict)
            else:
                d2.append(row_dict)
            data1 = a2 + b2 + c2 + e2 + f2 + d2

        returnDict = {'code': 200, 'message': '操作成功', "data": data1[num1:num2], "num": rows1_num[0]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class notice_change(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returnData = {'realname': real_name, 'position': position, 'department': department}

        return render(request, 'announcements/notice_change.html', returnData)


class MyAnnouncementList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returnData = {'realname': real_name, 'position': position, 'department': department}
        return render(request, 'announcements/MyAnnouncementList.html', returnData)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = Notice.objects.filter(create_people=request.user).order_by('-create_time')
        data_list = [{'id': temp.id, 'is_open': temp.is_open,
                      'department': temp.create_people.department,
                      'status': temp.get_state_str(),
                      'cut_people': ", ".join([t.real_name for t in temp.current_audit_users.all()]),
                      'create_user': temp.create_people.real_name,
                      'create_time': temp.update_time.strftime("%Y-%m-%d %H:%M"), 'titile': temp.name} for
                     temp in objs]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



def GetTopicDict(topic_id):
    print(topic_id)
    one_dict = {}
    yiti_yb_obj = Topics.objects.get(id=int(topic_id))
    one_dict["help_department"] = ' ,'.join([i.name for i in yiti_yb_obj.help_department.all()])
    one_dict["title"] = yiti_yb_obj.topics_name
    one_dict["dep"] = yiti_yb_obj.employee.department
    one_dict["tjr"] = yiti_yb_obj.employee.real_name
    one_dict["ytbh"] = yiti_yb_obj.number
    one_dict["ygys"] = yiti_yb_obj.topics_estimate
    one_dict["nrwb"] = yiti_yb_obj.nrwb
    one_dict["zcyj"] = yiti_yb_obj.zcwb
    one_dict["fawb"] = yiti_yb_obj.fawb
    one_dict["ysje"] = yiti_yb_obj.ysje
    one_dict["jfly"] = yiti_yb_obj.jfly
    one_dict["nrwb_base"] = yiti_yb_obj.topics_text
    one_dict["fawb_base"] = yiti_yb_obj.solution
    one_dict["zcyj_base"] = yiti_yb_obj.topics_basis
    audit_dic = {}
    for audit_obj in yiti_yb_obj.topicsauditrecord_set.all():
        if audit_obj.node in audit_dic:
            audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                              'state': audit_obj.get_state_display(),
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': os.getcwd() + '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
        else:
            audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                          'state': audit_obj.get_state_display(),
                                          'node': audit_obj.node,
                                          'node_display': audit_obj.get_node_display(),
                                          'audit_note': audit_obj.audit_note,
                                          'audit_time': audit_obj.update_time.strftime(
                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                          'signature_picture': os.getcwd() + '/media/' + str(
                                              audit_obj.audit_people.signature_picture) if (
                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

    one_dict["audit_dic"] = audit_dic
    return one_dict, yiti_yb_obj


# 院办议题上会
class HospitalOfficeMeeting(View):
    def post(self, request):
        id_list = request.POST.get("id_list", None)
        file_name = request.POST.get("file_name", None)
        iss_type = request.POST.get("iss_type", None)
        meeting_adress = request.POST.get("meeting_adress", None)
        meeting_time = request.POST.get("meeting_time", None)
        notification = request.POST.get("notification", None)
        ConferenceHost = request.POST.get("ConferenceHost", None)
        RecordAndPush().OperationRecords(request, "院办议题上会")
        # *********************************** 生成pdf文件 ****************************************
        pdf_file_list = []
        page_list = []
        for i in json.loads(id_list):
            one_dict = {}
            yiti_yb_obj = Topics.objects.get(id=int(i))
            one_dict["help_department"] = ' ,'.join([i.name for i in yiti_yb_obj.help_department.all()])
            one_dict["title"] = yiti_yb_obj.topics_name
            one_dict["dep"] = yiti_yb_obj.employee.department
            one_dict["tjr"] = yiti_yb_obj.employee.real_name
            one_dict["ytbh"] = yiti_yb_obj.number
            one_dict["ygys"] = yiti_yb_obj.topics_estimate
            one_dict["nrwb"] = yiti_yb_obj.nrwb
            one_dict["zcyj"] = yiti_yb_obj.zcwb
            one_dict["fawb"] = yiti_yb_obj.fawb
            one_dict["ysje"] = yiti_yb_obj.ysje
            one_dict["jfly"] = yiti_yb_obj.jfly
            one_dict["nrwb_base"] = yiti_yb_obj.topics_text
            one_dict["fawb_base"] = yiti_yb_obj.solution
            one_dict["zcyj_base"] = yiti_yb_obj.topics_basis
            audit_dic = {}
            for audit_obj in yiti_yb_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': os.getcwd() + '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': os.getcwd() + '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            one_dict["audit_dic"] = audit_dic
            file_path = topic_directory().yb_func(one_dict, iss_type, file_name)

            pdf_file_list.append(file_path)
            text_page = get_num_pages(file_path)
            pdf_path_list = Topicsattachments.objects.filter(topics_number=yiti_yb_obj.uuid, file_type="0")
            for path in pdf_path_list:
                pdf_file_path = os.getcwd() + path.pdf_path
                if path.file_name.split(".")[-1] not in ['pptx', 'ppt', 'PPT']:
                    if path.pdf_path.split('.')[1] in ['pdf', 'PDF']:
                        pdf_file_list.append(pdf_file_path)
                        enclosure_page = get_num_pages(pdf_file_path)
                        text_page += enclosure_page
                    elif path.pdf_path.split('.')[-1] in ["JPG", "JPEG", "PNG", "jpg", "jpeg", "png"]:
                        pdf_tp_path = image_to_pdf(pdf_file_path)
                        pdf_file_list.append(pdf_tp_path)
                        enclosure_page = get_num_pages(pdf_tp_path)
                        text_page += enclosure_page

            page_list.append(text_page)

        file_merger = PdfFileMerger(strict=False)  # 创建存放多个pdf文件的对象
        for pdf in pdf_file_list:
            try:
                file_merger.append(pdf)  # 合并pdf文件
            except:
                continue
        Issue_information_path = os.getcwd() + "/media/" + "Issue_information/pdf_file"
        if not os.path.exists(Issue_information_path):
            os.makedirs(Issue_information_path)
        pdf_path = f"{Issue_information_path}/{file_name}-会议资料_numbered.pdf"  # PDF 议题资料路径
        file_merger.write(pdf_path)
        if os.path.exists(f"{Issue_information_path}/{file_name}-会议资料.pdf"):
            os.remove(f"{Issue_information_path}/{file_name}-会议资料.pdf")
        os.rename(pdf_path, f"{Issue_information_path}/{file_name}-会议资料.pdf")

        # add_page_numgers(pdf_path)
        mobiles, all_db_data_list = [], []
        # *********************************** 生成excel文件 ****************************************
        DbAllList, YbAllList, XzAllList, DbDict, YbDict, LhDict, IdList = [], [], [], {}, {}, {}, []
        DirectorMobile = {}
        Yb_AllList = []
        for i in range(len(json.loads(id_list))):
            Ybobj = Topics.objects.get(id=int(json.loads(id_list)[i]))
            if Ybobj.employee.mobile in DirectorMobile:
                if len(DirectorMobile[Ybobj.employee.mobile]) > 1:
                    DirectorMobile[Ybobj.employee.mobile][1] = i+1
                else:
                    DirectorMobile[Ybobj.employee.mobile].append(i+1)
            else:
                DirectorMobile[Ybobj.employee.mobile] = [i+1]
            TOPICTYPE = '付款类' if Ybobj.topic_type == '1' else "经济合同类" if Ybobj.topic_type == '2' else "项目类" if Ybobj.topic_type == '3' else "文件类" if Ybobj.topic_type == '4' else "方案类" if Ybobj.topic_type == '5' else "其他事项" if Ybobj.topic_type == '6' else ""

            yb_list = [Ybobj.topics_name, Ybobj.employee.department, Ybobj.employee.real_name, str(Ybobj.create_time).split(".")[0][:-3],
                       str(Ybobj.topicsauditrecord_set.all().order_by('update_time').last().update_time).split(".")[0][:-3],
                       Ybobj.employee.company.leaders_id.real_name, Ybobj.id, TOPICTYPE]

            if Ybobj.employee.department in YbDict:
                YbDict[Ybobj.employee.department].append(yb_list)
            else:
                YbDict[Ybobj.employee.department] = [yb_list]

        for iJ in YbDict:
            Yb_AllList += YbDict[iJ]

        for ij in range(len(Yb_AllList)):
            Yb_AllList[ij].insert(0, ij + 1)
            start_page = sum(page_list[:ij]) + 1
            end_page = sum(page_list[:ij + 1])
            page_number = f"{start_page}-{end_page}页"
            if start_page == end_page:
                page_number = f"{start_page}页"
            Yb_AllList[ij].append(page_number)
            YbAllList.append(Yb_AllList[ij])

        file_path = os.getcwd() + f"/media/Issue_information/excel_file/{iss_type}"
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        # if int(notification):
        #     create_table().send_msg(YbAllList, file_name, meeting_time, meeting_adress)
        create_table().yb_excel(YbAllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)
        for ids in YbAllList:
            IdList.append(ids[-2])

        now_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        now_year = now_time.split('-')[0]
        meet_num_list = Topics.objects.filter(type=f'{iss_type}', iss_year=now_year).values("meetings_num")
        meet_num = int(max([int(i["meetings_num"]) for i in meet_num_list])) + 1 if meet_num_list else 1

        real_name_list, job_num_list, message_content = [], [], f'<p>尊敬的院领导：</p><p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; 您好！<span style="color: rgb(255, 0, 0);">{file_name}&nbsp;</span>将于&nbsp;<span style="color: rgb(255, 0, 0);">{str(meeting_time).split(".")[0][:-3]}</span>&nbsp;在&nbsp;' \
                                                                f'<span style="color: rgb(255, 0, 0);">{meeting_adress}</span>&nbsp;召开</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;该信息为您送来了本次会议的资料，包括&nbsp;<span style="color: rgb(255, 0, 0);">会议文件&nbsp;</span>的汇总和&nbsp;<span style="color: rgb(255, 0, 0);">议题目录</span>。</p>' \
                                                                f'<p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; 详情请见附件内容！</p><p><br/></p><p><br/></p><p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' \
                                                                f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {time.strftime("%Y 年 %m 月 %d 日", time.localtime())}</p><p><br style="white-space: normal;"/></p><p><br/></p>'

        file_path = [{"file_name": f"{file_name}-会议资料.pdf", "file_path": pdf_path.replace(os.getcwd(), '')}, {"file_name": f"{file_name}-会议目录.xlsx",
                      "file_path": (file_path + f"/{file_name}-会议目录.xlsx").replace(os.getcwd(), '')}]

        attending_leaders = request.POST.get("attending_leaders", '')
        if attending_leaders:
            leader_list = attending_leaders.split(",")
            for lea in leader_list:
                if lea.strip():
                    LeadersObj = User.objects.get(id=int(lea.strip()))
                    real_name_list.append(LeadersObj.real_name)
                    job_num_list.append(LeadersObj.job_number)
                    if LeadersObj.mobile.strip():
                        mobiles.append(LeadersObj.mobile)
        else:
            user_obj = User.objects.filter(Q(group_id="1") | Q(group_id="2"))
            meet_people_obj = Staffing.objects.get(station='开会按钮可见').post_personnel.all()
            for t in user_obj:
                if t in meet_people_obj:
                    real_name_list.append(t.real_name)
                    job_num_list.append(t.job_number)
                    if t.mobile.strip():
                        mobiles.append(t.mobile)
        meet_year = re.findall("(.*?)年", file_name)[0]
        meet_number = re.findall("第(.*?)次", file_name)[0]
        content = '您好！%s 将于 %s 在 %s 召开, 若您需要请假，请点击https://oaapi.hbjsxrmyy.com/personal-center/ConfirmAttendance.html?type=yb&year=%s&number=%s，若无需请假，可忽略此信息！' % (file_name, str(meeting_time).split(".")[0][:-3], meeting_adress, meet_year, meet_number)

        mobiles = list(set(mobiles))
        if int(notification):
            res = send_mssage(mobiles, content)
            for keys in DirectorMobile:
                if len(DirectorMobile[keys]) > 1:
                    DirectorContent = f'您好！{file_name}将于{str(meeting_time).split(".")[0][:-3]}在{meeting_adress}召开，您的议题位于第{DirectorMobile[keys][0]}至{DirectorMobile[keys][1]}个，请按时参加！'
                else:
                    DirectorContent = f'您好！{file_name}将于{str(meeting_time).split(".")[0][:-3]}在{meeting_adress}召开，您的议题位于第{DirectorMobile[keys][0]}个，请按时参加！'
                res1 = send_mssage([keys], DirectorContent)

        unique = uuid.uuid4()

        InboxInfo_obj = InboxInfo.objects.create(
            content=message_content,
            plain_text=f'尊敬的院领导： 您好！{file_name}将于{str(meeting_time).split(".")[0][:-3]}在{meeting_adress}召开，该信息为您送来了本次会议的资料，包括：会议文件的汇总和，议题目录， 详情请见附件内容;  {time.strftime("%Y 年 %m 月 %d 日", time.localtime())}',
            title=file_name, accessory_uuid=unique, is_draft=False, proposer=request.user)

        for i in job_num_list:
            user_obj = User.objects.get(job_number=i)
            InboxInfoPeople.objects.create(inbox_id=InboxInfo_obj, recipient=user_obj, recipient_name=f"{user_obj.real_name}<{user_obj.job_number}>")

        achments_objs = Topicsattachments.objects.filter(topics_number=InboxInfo_obj.accessory_uuid)
        for achments_obj in achments_objs:
            achments_obj.watch_users.add(InboxInfo_obj.proposer)
            for r in InboxInfo_obj.inboxinfopeople_set.all():
                if r.audit_people not in achments_obj.watch_users.all():
                    achments_obj.watch_users.add(r.audit_people)

        for ttt in file_path:
            Topicsattachments.objects.create(
                topics_number=unique, file_size='', file_path=ttt["file_path"].replace("_numbered", ""), uploader=request.user.real_name, uploader_user=request.user,
                file_type='1', pdf_path=ttt["file_path"].replace("_numbered", ""), file_name=ttt["file_name"], source='yx')

        ScanCode.objects.create(type='1', topic_year=now_year, meet_number=meet_num)
        for T in json.loads(id_list):
            Top_obj = Topics.objects.get(id=int(T))
            Top_obj.meetings_num = meet_num
            Top_obj.iss_year = now_year
            Top_obj.is_meeting = 'b'
            Top_obj.state = 'metting'
            Top_obj.save()

            topic_meeting.objects.create(meet_number=meet_num, topic_type=Top_obj.type, meet_time=meeting_time, topic_year=Top_obj.iss_year, topic=Top_obj, compere=User.objects.get(id=int(ConferenceHost)))
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 院办议题临时上会
class HospitalOfficeMeetingTemporary(View):
    def post(self, request):
        id_list = request.POST.get("id_list", None)  # 临时上会id列表
        sh_type = request.POST.get("sh_type", False)  # 上会类型
        now_year = datetime.now().year
        RecordAndPush().OperationRecords(request, "院办议题临时上会")
        meetings_num_list = Topics.objects.filter(type=sh_type, iss_year=str(now_year), is_meeting='b')
        max_meetings_num = max([int(i.meetings_num) for i in meetings_num_list]) if [int(i.meetings_num) for i in meetings_num_list] else 0
        if max_meetings_num == 0:
            now_year = int(now_year) - 1
            meetings_num_list = Topics.objects.filter(type=sh_type, iss_year=str(now_year))
            max_meetings_num = max([int(i.meetings_num) for i in meetings_num_list])

        # *********************************** 生成pdf文件 ****************************************
        already_meet = topic_meeting.objects.filter(topic_type=sh_type, meet_number=max_meetings_num, topic_year=now_year).first()
        if already_meet.state != 'notstart':
            returnDict = {'code': 400, 'message': '会议已经开始，无法临时上会！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        for i in json.loads(id_list):
            yiti_yb_obj = Topics.objects.get(id=int(i))
            yiti_yb_obj.meetings_num = max_meetings_num
            yiti_yb_obj.is_meeting = 'b'
            yiti_yb_obj.iss_yesr = now_year
            yiti_yb_obj.state = "metting"
            yiti_yb_obj.save()

            meet_obj = topic_meeting.objects.create(meet_number=max_meetings_num, topic_type=yiti_yb_obj.type, meet_time=already_meet.meet_time, topic_year=already_meet.topic_year, topic=yiti_yb_obj, compere=already_meet.compere)

        returnDict = {'code': 200, 'message': ''}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 党办议题上会
class PartyOfficeMeeting(View):
    def post(self, request):
        id_list = request.POST.get("id_list", None)
        file_name = request.POST.get("file_name", None)
        iss_type = request.POST.get("iss_type", None)
        meeting_adress = request.POST.get("meeting_adress", None)
        meeting_time = request.POST.get("meeting_time", None)
        notification = request.POST.get("notification", None)
        ConferenceHost = request.POST.get("ConferenceHost", None)
        pass_yb_list = []
        no_pass_yb = []
        RecordAndPush().OperationRecords(request, "党办议题上会")
        for ii in json.loads(id_list):
            yiti_db_obj = Topics.objects.get(id=int(ii))
            if yiti_db_obj.is_yb:
                pass_yb_list.append(ii)
            else:
                no_pass_yb.append(ii)
        id_list = json.dumps(pass_yb_list + no_pass_yb)
        # *********************************** 生成PDF文件 ****************************************
        pdf_file_list, pass_yb_page_list, nopass_yb_page_list = [], [], []
        for i in pass_yb_list:
            one_dict, yiti_obj = GetTopicDict(i)
            file_path = topic_directory().db_func(one_dict, iss_type, file_name)

            pdf_file_list.append(file_path)
            text_page = get_num_pages(file_path)
            pdf_path_list = Topicsattachments.objects.filter(topics_number=yiti_obj.uuid, file_type="0")
            for path in pdf_path_list:
                pdf_file_path = os.getcwd() + path.pdf_path
                if path.file_name.split(".")[-1] not in ['pptx', 'ppt']:
                    if path.pdf_path.split('.')[1] in ['pdf', 'PDF']:
                        pdf_file_list.append(pdf_file_path)
                        enclosure_page = get_num_pages(pdf_file_path)
                        text_page += enclosure_page
                    elif path.pdf_path.split('.')[-1] in ["JPG", "JPEG", "PNG", "jpg", "jpeg", "png"]:
                        pdf_tp_path = image_to_pdf(pdf_file_path)
                        pdf_file_list.append(pdf_tp_path)
                        enclosure_page = get_num_pages(pdf_tp_path)
                        text_page += enclosure_page
            pass_yb_page_list.append(text_page)

        for i in no_pass_yb:
            one_dict, no_yiti_obj = GetTopicDict(i)
            file_path = topic_directory().db_func(one_dict, iss_type, file_name)
            pdf_file_list.append(file_path)
            text_page = get_num_pages(file_path)
            pdf_path_obj = Topicsattachments.objects.filter(topics_number=no_yiti_obj.uuid, file_type="0")
            for path in pdf_path_obj:
                pdf_file_path = os.getcwd() + path.pdf_path
                if path.file_name.split(".")[-1] not in ['pptx', 'ppt']:
                    if path.pdf_path.split('.')[1] in ['pdf', 'PDF']:
                        pdf_file_list.append(pdf_file_path)
                        enclosure_page = get_num_pages(pdf_file_path)
                        text_page += enclosure_page
                    elif path.pdf_path.split('.')[-1] in ["JPG", "JPEG", "PNG", "jpg", "jpeg", "png"]:
                        pdf_tp_path = image_to_pdf(pdf_file_path)
                        pdf_file_list.append(pdf_tp_path)
                        enclosure_page = get_num_pages(pdf_tp_path)
                        text_page += enclosure_page
            nopass_yb_page_list.append(text_page)

        page_list = pass_yb_page_list + nopass_yb_page_list

        file_merger = PdfFileMerger(strict=False)  # 创建存放多个pdf文件的对象
        for pdf in pdf_file_list:
            file_merger.append(pdf)  # 合并pdf文件
        Issue_information_path = os.getcwd() + "/media/" + "Issue_information/pdf_file"
        if not os.path.exists(Issue_information_path):
            os.makedirs(Issue_information_path)
        pdf_path = f"{Issue_information_path}/{file_name}-会议资料.pdf"  # PDF 议题资料路径
        file_merger.write(pdf_path)

        mobiles, all_db_data_list = [], []
        # *********************************** 生成excel文件 ****************************************
        YbZhuanDbAllList, YbZhuanDbAllDict, YbDbAllDict, Db_AllList, Db_zh_alllidt, Db_all_list, Yb_ZhuanDbAllList, DbAllList = [], {}, {}, [], [], [], [], []
        PassYbDict, NoPassYbDict = [], []
        for pass_yb in pass_yb_list:
            PassYbObj = Topics.objects.get(id=int(pass_yb))
            PassYbDict.append([PassYbObj.topics_name, PassYbObj.employee.department, PassYbObj.employee.real_name, str(PassYbObj.create_time).split(".")[0][:-3], str(PassYbObj.update_time).split(".")[0][:-3],
                       PassYbObj.employee.company.director if PassYbObj.employee.company.director else PassYbObj.employee.company.deputy_director, PassYbObj.id])

        for nopass_yb in no_pass_yb:
            NoPassYbObj = Topics.objects.get(id=int(nopass_yb))
            NoPassYbDict.append([NoPassYbObj.topics_name, NoPassYbObj.employee.department, NoPassYbObj.employee.real_name, str(NoPassYbObj.create_time).split(".")[0][:-3], str(NoPassYbObj.update_time).split(".")[0][:-3],
                       NoPassYbObj.employee.company.director if NoPassYbObj.employee.company.director else NoPassYbObj.employee.company.deputy_director, NoPassYbObj.id])


        for TT in range(len(PassYbDict)):
            PassYbDict[TT].insert(0, TT + 1)
            new_list = PassYbDict[TT][:2]
            new_list.append(PassYbDict[TT][-1])
            YbZhuanDbAllList.append(new_list)

        for TJ in range(len(NoPassYbDict)):
            NoPassYbDict[TJ].insert(0, TJ + 1)
            Db_AllList.append(NoPassYbDict[TJ])

        all_db_data_list = YbZhuanDbAllList + Db_AllList


        for ij in range(len(YbZhuanDbAllList)):
            start_page = sum(page_list[:ij]) + 1
            end_page = sum(page_list[:ij + 1])
            page_number = f"{start_page}-{end_page}页"
            if start_page == end_page:
                page_number = f"{start_page}页"
            YbZhuanDbAllList[ij].append(page_number)
            Yb_ZhuanDbAllList.append(YbZhuanDbAllList[ij])

        page_start = len(YbZhuanDbAllList)
        for ij in range(len(Db_AllList)):
            start_page = sum(page_list[:page_start]) + 1
            end_page = sum(page_list[:page_start + 1])
            page_number = f"{start_page}-{end_page}页"
            if start_page == end_page:
                page_number = f"{start_page}页"
            Db_AllList[ij].append(page_number)
            DbAllList.append(Db_AllList[ij])
            page_start += 1

        file_path = os.getcwd() + f"/media/Issue_information/excel_file/db"
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        # if int(notification):
        #     create_table().send_msg(DbAllList, file_name, meeting_time, meeting_adress, ty="db")
        create_table().db_excel(Yb_ZhuanDbAllList, DbAllList, file_path + f"/{file_name}-会议目录.xlsx", file_name)

        now_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        now_year = now_time.split('-')[0]
        meet_num_list = Topics.objects.filter(type=f'{iss_type}', iss_year=now_year).values("meetings_num")
        meet_num = int(max([int(i["meetings_num"]) for i in meet_num_list])) + 1 if meet_num_list else 1

        real_name_list, job_num_list, message_content = [], [], f'<p>尊敬的院领导：</p><p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; 您好！<span style="color: rgb(255, 0, 0);">{file_name}&nbsp;</span>将于&nbsp;<span style="color: rgb(255, 0, 0);">{str(meeting_time).split(".")[0][:-3]}</span>&nbsp;在&nbsp;' \
                                                                f'<span style="color: rgb(255, 0, 0);">{meeting_adress}</span>&nbsp;召开</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;该信息为您送来了本次会议的资料，包括&nbsp;<span style="color: rgb(255, 0, 0);">会议文件&nbsp;</span>的汇总和&nbsp;<span style="color: rgb(255, 0, 0);">议题目录</span>。</p>' \
                                                                f'<p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; 详情请见附件内容！</p><p><br/></p><p><br/></p><p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' \
                                                                f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {time.strftime("%Y 年 %m 月 %d 日", time.localtime())}</p><p><br style="white-space: normal;"/></p><p><br/></p>'

        file_path = [{"file_name": f"{file_name}-会议资料.pdf", "file_path": pdf_path.replace(os.getcwd(), '')},
                     {"file_name": f"{file_name}-会议目录.xlsx", "file_path": (file_path + f"/{file_name}-会议目录.xlsx").replace(os.getcwd(), '')}]

        user_obj = User.objects.filter(Q(group_id="1") | Q(group_id="2"))
        for t in user_obj:
            real_name_list.append(t.real_name)
            job_num_list.append(t.job_number)
            if t.mobile.strip():
                mobiles.append(t.mobile)
        meet_year = re.findall("(.*?)年", file_name)[0]
        meet_number = re.findall("第(.*?)次", file_name)[0]
        content = '您好！%s 将于 %s 在 %s 召开, 若您需要请假，请点击https://oaapi.hbjsxrmyy.com/personal-center/ConfirmAttendance.html?type=yb&year=%s&number=%s，若无需请假，可忽略此信息！' % (file_name, str(meeting_time).split(".")[0][:-3], meeting_adress, meet_year, meet_number)
        mobiles = list(set(mobiles))
        if int(notification):
            res = send_mssage(mobiles, content)

        unique = uuid.uuid4()

        InboxInfo_obj = InboxInfo.objects.create(
            plain_text=f'尊敬的院领导： 您好！{file_name}将于{str(meeting_time).split(".")[0][:-3]}在{meeting_adress}召开，该信息为您送来了本次会议的资料，包括：会议文件的汇总和，议题目录， 详情请见附件内容;  {time.strftime("%Y 年 %m 月 %d 日", time.localtime())}',
            title=file_name, accessory_uuid=unique, is_draft=False, proposer=request.user, content=message_content
        )

        for i in job_num_list:
            user_obj = User.objects.get(job_number=i)
            InboxInfoPeople.objects.create(inbox_id=InboxInfo_obj, recipient=user_obj, recipient_name=f"{user_obj.real_name}<{user_obj.job_number}>")

        achments_objs = Topicsattachments.objects.filter(topics_number=InboxInfo_obj.accessory_uuid)
        for achments_obj in achments_objs:
            achments_obj.watch_users.add(InboxInfo_obj.proposer)
            for r in InboxInfo_obj.inboxinfopeople_set.all():
                if r.audit_people not in achments_obj.watch_users.all():
                    achments_obj.watch_users.add(r.audit_people)

        for ttt in file_path:
            Topicsattachments.objects.create(
                topics_number=unique, file_size='', file_path=ttt["file_path"].replace("_numbered", ""), uploader=request.user.real_name, uploader_user=request.user,
                file_type='1', pdf_path=ttt["file_path"].replace("_numbered", ""), file_name=ttt["file_name"], source='yx'
            )

        for T in json.loads(id_list):
            Top_obj = Topics.objects.get(id=int(T))
            Top_obj.meetings_num = meet_num
            Top_obj.iss_year = now_year
            Top_obj.is_meeting = 'b'
            Top_obj.state = 'metting'
            Top_obj.save()

        ScanCode.objects.create(type='2', topic_year=now_year, meet_number=meet_num)
        for ji in all_db_data_list:
            DbTopObj = Topics.objects.get(id=int(ji[-2]))
            topic_meeting.objects.create(meet_number=meet_num, topic_type=DbTopObj.type, meet_time=meeting_time, topic_year=DbTopObj.iss_year, topic=DbTopObj, compere=User.objects.get(id=int(ConferenceHost)))

        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 党办议题临时上会
class PartyOfficeMeetingTemporary(View):
    def post(self, request):
        id_list = request.POST.get("id_list", None)  # 临时上会id列表
        sh_type = request.POST.get("sh_type", False)  # 上会类型
        now_year = datetime.now().year
        RecordAndPush().OperationRecords(request, "党办议题临时上会")
        meetings_num_list = Topics.objects.filter(type=sh_type, iss_year=str(now_year), is_meeting='b')
        max_meetings_num = max([int(i.meetings_num) for i in meetings_num_list]) if [int(i.meetings_num) for i in meetings_num_list] else 0
        if max_meetings_num == 0:
            now_year = int(now_year) - 1
            meetings_num_list = Topics.objects.filter(type=sh_type, iss_year=str(now_year))
            max_meetings_num = max([int(i.meetings_num) for i in meetings_num_list])

        # *********************************** 生成pdf文件 ****************************************
        TopMetObj = topic_meeting.objects.filter(meet_number=max_meetings_num, topic_type='db', topic_year=now_year)

        if TopMetObj.first().state != 'notstart':
            returnDict = {'code': 400, 'message': '会议已经开始，无法临时上会！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        meet_time = TopMetObj.first().meet_time
        file_name = f"{now_year}年第{max_meetings_num}次党委会"
        for i in json.loads(id_list):
            yiti_yb_obj = Topics.objects.get(id=int(i))
            yiti_yb_obj.meetings_num = max_meetings_num
            yiti_yb_obj.is_meeting = 'b'
            yiti_yb_obj.iss_yesr = now_year
            yiti_yb_obj.state = "metting"
            yiti_yb_obj.save()

            topic_meeting.objects.create(meet_number=max_meetings_num, topic_type='db', meet_time=meet_time, topic_year=now_year, topic=yiti_yb_obj, compere=TopMetObj.first().compere)

        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ChangeMeetingOrder(View):
    def post(self, request):
        id_list = request.POST.get("id_list", [])  # 开会id顺序列表
        page_number = request.POST.get("page_number", 1)  # 页码
        PageNumber = request.POST.get("PageNumber", 20)  # 每页数量

        first_obj = topic_meeting.objects.get(id=json.loads(id_list)[0])

        # 修改之前的数据
        AfterModificationObj = topic_meeting.objects.filter(meet_number=first_obj.meet_number, topic_type=first_obj.topic_type, topic_year=first_obj.topic_year).order_by('id')[(int(page_number) - 1) * int(PageNumber):int(page_number) * int(PageNumber)]

        NewModificationObj = []
        for i in json.loads(id_list):
            NewModificationObj.append(topic_meeting.objects.get(id=int(i)).topic.id)

        count_number = 0
        for obj in AfterModificationObj:
            obj.topic_id = NewModificationObj[count_number]
            obj.update_time = datetime.now()
            obj.save()
            count_number += 1

        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")